"""封装所有mysql操作"""
import logging

import pymysql
from pymysql.cursors import DictCursor
from config.config import *
from utils.exception_utils import MysqlException
from utils.logger_utils import *


class MysqlUtils:

    def __init__(self):
        self.__conn = None
        try:
            self.__conn = self.connect_mysql()
        except Exception as e :
            info("数据库连接失败！")
            raise MysqlException

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.__conn :
            self.__conn.close()

    @staticmethod
    def connect_mysql():
        info(f"数据库连接配置：{SQL_CONNECTION}")
        conn = pymysql.connect(**SQL_CONNECTION)
        info(f"数据库连接配置成功！")
        return conn

    def send_sql_one(self,sql):
        with self.__conn.cursor(DictCursor) as cur :
            cur.execute(sql)
            res = cur.fetchone()
            info(f"查看数据库返回：{res}")
            return res


    def send_sql_all(self,sql):
        with self.__conn.cursor(DictCursor) as cur :
            cur.execute(sql)
            res = cur.fetchall()
            return res

